﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using EventAggregator;

namespace EAWpfSample
{
    public sealed class MyApp : IDisposable
    {
        private readonly Thread _backgroundTimerThread;
        private readonly EventMessageHandler _handlerAppShutdown;
        private readonly EventMessageHandler _handlerAppStartup;
        private readonly EventMessageHandler _handlerDoWork;

        public MyApp()
        {
            _backgroundTimerThread = new Thread(TimerThread)
                {
                    Name = "Timer Thread",
                    IsBackground = true
                };

            _handlerDoWork = this.Subscribe(EventId.Default.DoWork, HandleDoWork);
            _handlerAppStartup = this.Subscribe(EventId.Default.AppStartup, HandleAppStartup);
            _handlerAppShutdown = this.Subscribe(EventId.Default.AppShutdown, HandleAppShutdown);
        }

        #region IDisposable Members

        public void Dispose()
        {
            _handlerAppStartup.Dispose();
            _handlerAppShutdown.Dispose();
            _handlerDoWork.Dispose();
        }

        #endregion

        private void HandleAppStartup(EventMessage eventMessage)
        {
            _backgroundTimerThread.Start();
        }

        private void TimerThread(object parameter)
        {
            while (true)
            {
                this.Send(EventId.Default.TimerUpdate, new KeyValuePair<string, object>("DateTime", DateTime.Now));
                Thread.Sleep(1000);
            }
        }

        private void HandleAppShutdown(EventMessage eventMessage)
        {
            Dispose();
        }

        private void HandleDoWork(EventMessage eventMessage)
        {
            Task.Factory.StartNew(
                () =>
                    {
                        double interval = eventMessage.GetValue<TimeSpan>("TimeSpan").TotalSeconds;
                        for (int i = 1; i <= interval; i++)
                        {
                            Thread.Sleep(1000);
                            this.Send(EventId.Default.WorkProgress, new KeyValuePair<string, object>("Progress", i));
                        }

                        this.Send(EventId.Default.WorkDone, new KeyValuePair<string, object>("WorkIsDone", true));
                    });
        }
    }
}